import server from "../server/index.js"
import sql from "../sql/index.js"

async function closeApp() {
  // 1 关闭 sql
  await sql.backup()
  sql.close()
  // 2 关闭 express 服务器
  server.close(() => {
    process.exit(1);
  });
  // 3 1秒后自动退出，防止上述回调失效
  process.exit(1);
}

// 1 处理未捕获错误
process.on('uncaughtException', (err) => {
  console.log(`${err.name}: ${err.message}`);
  console.log('UNCAUGHT EXCEPTION! 🐱‍🏍 Shuting dow...');
  closeApp()
});

// 2 处理未捕获的 promise 错误
process.on('unhandledRejection', (err: Error) => {
  console.log(`${err.name}: ${err.message}`);
  console.log('UNHANDLER REJECTION! 🐱‍🏍 Shuting dow...');
  closeApp()
});

// 3 处理守护进程 pm2 意外关闭
process.on('SIGINT', (err: Error) => {
  console.log(`${err.name}: ${err.message}`);
  console.log('PM2 ERROR! 🐱‍🏍 Shuting dow...');
  closeApp()
})

console.log(`✔ : errorHandler start success`);
